import { useEffect } from "react"; // , useState
import {
  Handle,
  Position,
  useNodeConnections,
  useNodesData,
  useReactFlow,
} from "@xyflow/react";

function CustomHandle({ id, label, onChange }) {
  const connections = useNodeConnections({
    handleType: "target",
    handleId: id,
  });

  const nodeData = useNodesData(connections?.[0].source);

  useEffect(() => {
    onChange(nodeData?.data ? nodeData.data.value : 0);
  }, [nodeData]); //此处传递[onChange，nodeData]和不传递都会死循环

  return (
    <div
      className="nopan"
      onMouseDown={() => {
        console.log("aa");
      }}
      onMouseUp={() => {
        console.log("bb");
      }}
    >
      <Handle
        type="target"
        position={Position.Left}
        id={id}
        className="handle"
      />
      <label htmlFor="red" className="label">
        {label}
      </label>
    </div>
  );
}

function ColorPreview({ id, data }) {
  const { updateNodeData } = useReactFlow();

  // const redConnections = useNodeConnections({
  //   handleType: "target",
  //   handleId: "red",
  // });
  // const redNodeData = useNodesData(redConnections?.[0].source);

  // const greenConnections = useNodeConnections({
  //   handleType: "target",
  //   handleId: "green",
  // });
  // const greenNodeData = useNodesData(greenConnections?.[0].source);

  // const blueConnections = useNodeConnections({
  //   handleType: "target",
  //   handleId: "blue",
  // });
  // const blueNodeData = useNodesData(blueConnections?.[0].source);

  // const color = {
  //   r: blueNodeData?.data ? redNodeData.data.value : 0,
  //   g: greenNodeData?.data ? greenNodeData.data.value : 0,
  //   b: blueNodeData?.data ? blueNodeData.data.value : 0,
  // };
  // const color = { r: 0, g: 0, b: 0 };
  // const [color, setColor] = useState({ r: 0, g: 0, b: 0 });
  // console.log(data.value);
  //

  return (
    <div
      className="node"
      style={{
        background: data.value
          ? `rgb(${data.value.r}, ${data.value.g}, ${data.value.b})`
          : "rgb(0, 0, 0)",
      }}
    >
      <CustomHandle
        id="red"
        label="R"
        onChange={(value) => {
          updateNodeData(id, (node) => {
            return { value: { ...node.data.value, r: value } };
          });
        }}
      />
      <CustomHandle
        id="green"
        label="G"
        onChange={(value) => {
          updateNodeData(id, (node) => {
            return { value: { ...node.data.value, g: value } };
          });
        }}
      />
      <CustomHandle
        id="blue"
        label="B"
        onChange={(value) =>
          updateNodeData(id, (node) => {
            return { value: { ...node.data.value, b: value } };
          })
        }
      />
      <Handle type="source" position={Position.Right} />
    </div>
  );
}

export default ColorPreview;
